// 函数组件
import React, { useEffect, useState } from 'react'
import './css/Authority.less'
import { Button, Table, Switch, Modal, Space } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { ConfigProvider } from 'antd';
import zh_CN from 'antd/es/locale/zh_CN';
import AddAuthority from './child/AddAuthority'
import EditAuthority from './child/EditAuthority';
import { getRoles, delRoles, updataState } from '../../../api/authority';
import getSelectTime from '../../../utils/date'
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import { ExclamationCircleOutlined } from '@ant-design/icons';


interface DataType {
    key: React.Key;
    id: Number;
    RoleName: string;
    FunctionalDescription: string;
    member: Number;
    CreationTime: string;
    isGo: Number;
}

interface rolesType {
    roleId: number,
    createTime: string,
    roleJob: string,
    roleName: string,
    roleNum: number,
    roleState: number,
}

interface menuType {
    menuId: number,
    des: string,
    menuName: string,
    menuRemark: string,
    menuUrl: null,
    pid: number,
    icon: null
}
function RoleManagement() {
    const [isAdd, setIsAdd] = useState<boolean>(false)
    const [isEdit, setIsEdit] = useState<boolean>(false)
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [loading, setLoading] = useState<boolean>(false);
    const [editValue, setEditValue] = useState<DataType | null>(null)  //点击的哪一行数据
    const [rolesList, setRolesList] = useState<rolesType[]>([]) //装成员信息
    const [menuList, setMenuList] = useState<menuType[]>([]) //装权限菜单
    const [isGO, setIsGo] = useState<number>(0);
    useEffect(() => {
        showRoles()
    }, [])

    const start = () => {
        setLoading(true);
        // ajax request after empty completing
        setTimeout(() => {
            setSelectedRowKeys([]);
            setLoading(false);
        }, 1000);
    };
    const showRoles = () => {
        getRoles().then(res => {
            console.log('所有信息', res);
            let newRoles = res.data.roleMenus.map(function (item: rolesType) {
                item.createTime = getSelectTime(item.createTime)
                return item
            })
            // console.log(newRoles);
            // dayjs.extend(utc)
            setMenuList(res.data.menuListAll)
            // console.log("time", dayjs.utc(new Date()).format())
            setRolesList(newRoles)
        }).catch(err => {
            console.log('所有信息', err);
        })
    }

    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };


    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };
    const hasSelected = selectedRowKeys.length > 0;
    const onChange = (checked: boolean) => {
        console.log(`switch to ${checked}`);
        if (checked == true) {
            setIsGo(1)
        } else if (checked == false) {
            setIsGo(0)
        }
        console.log(isGO);
        
    };
    const State = (value: DataType) => {
        console.log(value);
        updataState({ roleId: value.id, state: isGO }).then(res => {
            console.log('所有信息', res);
            showRoles()
        }).catch(err => {
            console.log('所有信息', err);
        })
    }
    const columns: ColumnsType<DataType> = [
        {
            title: '序号',
            dataIndex: 'id',
            width: '10%',
            align: 'center'
        },
        {
            title: '角色名称',
            dataIndex: 'RoleName',
            width: '13%',
            align: 'center'
        },
        {
            title: '职能描述',
            dataIndex: 'FunctionalDescription',
            width: '20%',
            align: 'center'
        },
        {
            title: '成员',
            dataIndex: 'member',
            width: '10%',
            align: 'center'
        },
        {
            title: '创建时间',
            dataIndex: 'CreationTime',
            width: '12%',
            align: 'center'
        },
        {
            title: '是否启用',
            dataIndex: 'isGo',
            width: '15%',
            align: 'center',
            render: (_, record) => (
                <div>
                    <Switch defaultChecked={record.isGo == 1 ? true : false} onChange={onChange} onClick={() => State(record)} />
                </div>
            ),
        },
        {
            title: '操作',
            dataIndex: 'operation',
            width: '20%',
            align: 'center',
            render: (_, record) => (
                <div>
                    <button className='edit' onClick={() => openEdit(record)}>编辑</button>
                    <button className='del' onClick={() => del(record)}>删除</button>
                </div>
            ),
        },
    ];

    const data: DataType[] = [];
    for (let i = 0; i < rolesList.length; i++) {
        data.push({
            key: i,
            id: rolesList[i].roleId,
            RoleName: rolesList[i].roleName,
            FunctionalDescription: rolesList[i].roleJob,
            member: rolesList[i].roleNum,
            CreationTime: rolesList[i].createTime,
            isGo: rolesList[i].roleState
        });
    }

    //批量删除
    const BatchDeletion = () => {
        console.log('批量删除');
        // console.log(selectedRowKeys);
        let delList: any = []
        rolesList.forEach(function (item, index) {
            selectedRowKeys.forEach(function (item2) {
                if (index == item2) {
                    delList.push(item.roleId)
                }
            })
        })
        // selectedRowKeys.forEach(function(item){
        //     delList.push(item)
        // })
        console.log(delList);

        delRoles(delList).then(res => {
            console.log('所有信息', res);
            showRoles()
        }).catch(err => {
            console.log('所有信息', err);
        })

    }

    //删除
    const { confirm } = Modal
    const del = (item: DataType) => {
        confirm({
            title: '确认删除',
            icon: <ExclamationCircleOutlined />,
            content: '是否删除该角色',
            onOk() {
                console.log('OK');
                console.log(item.id);
                let delList = []
                delList.push(item.id)
                console.log(delList);
                delRoles(delList).then(res => {
                    console.log('所有信息', res);
                    showRoles()
                }).catch(err => {
                    console.log('所有信息', err);
                })
            },
            onCancel() {
                console.log('Cancel');
            },
        });
    }

    //添加
    const addRole = () => {
        setIsAdd(true)

    }

    const closeAdd = () => {
        setIsAdd(false)
    }

    //编辑
    const openEdit = (item: DataType): void => {
        setIsEdit(true)
        setEditValue(item)
        // console.log(item);

    }

    const closeEdit = () => {
        setIsEdit(false)
    }
    return (
        <div className='Authority'>
            {/* 头部 */}
            <div className='page-top'>
                {/* 左边标题 */}
                <div className='page-title'>
                    <p>角色管理</p>
                </div>
            </div>

            {/* 内容区 */}
            <div className='page-context'>
                {/* 数据表部分 */}
                <div className='data-list'>
                    {/* 上部文字 */}
                    <div className='list-text'>
                        <p>数据列表</p>
                        <div>
                            <button className='batch-del' onClick={BatchDeletion}>批量删除</button>
                            <button className='add' onClick={addRole}>添加</button>
                        </div>
                    </div>
                    {/* 数据 */}
                    <div>
                        {/* <div >
                            <span >
                                {hasSelected ? `Selected ${selectedRowKeys.length} items` : ''}
                            </span>
                        </div> */}
                        <ConfigProvider locale={zh_CN}>
                            <Table
                                rowSelection={rowSelection}
                                columns={columns}
                                dataSource={data}

                                scroll={{ y: 444 }}
                                pagination={{
                                    position: ['bottomCenter'],
                                    defaultPageSize: 10,
                                    pageSizeOptions: [3, 5, 10, 15],
                                    showQuickJumper: true,
                                    showSizeChanger: true
                                }}
                                bordered
                            />
                        </ConfigProvider>
                    </div>
                    <AddAuthority isAdd={isAdd} closeAdd={closeAdd} showRoles={showRoles} menuList={menuList}></AddAuthority>
                    <EditAuthority isEdit={isEdit} closeEdit={closeEdit} editValue={editValue} menuList={menuList} showRoles={showRoles}></EditAuthority>
                </div>
            </div>
        </div>
    )
}

export default RoleManagement